package com.guxingke.gsb.parse;

import com.github.rjeschke.txtmark.Processor;
import com.guxingke.gsb.config.Constant;
import com.guxingke.gsb.model.IParseable;
import com.guxingke.gsb.model.Meta;
import com.guxingke.gsb.repo.GsbRepo;
import com.moandjiezana.toml.Toml;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

/**
 * Created by 孤星可 on 2015/11/16.
 *
 * @author guxingke
 * @since 2015/11/16
 */
public class Parser {
    private static final String HEADER_DELIMITER = "###";
    private static final String LINE_SEPARATOR = System.lineSeparator();
    private static final Toml toml = new Toml();

    public static Meta parseMeta(Path path) {
        StringBuilder header = new StringBuilder();
        String layout = null;
        try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;
            while ((line = br.readLine()) != null && !line.trim().startsWith(HEADER_DELIMITER)) {
                if (line.trim().startsWith("layout")) {
                    layout = parseLayout(line);
                }
                header.append(line).append(LINE_SEPARATOR);
            }

            StringBuilder content = new StringBuilder();
            while ((line = br.readLine()) != null) {
                content.append(line).append(LINE_SEPARATOR);
            }
            return new Meta(header.toString(), content.toString(), layout);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static IParseable parseParseable(Meta meta) {
        String layout = meta.getLayout();
        IParseable parseable = toml.parse(meta.getHeader()).to(Constant.LAYOUT_MAPPING.get(layout));
        String content = Processor.process(meta.getContent());
        parseable.setContent(content);
        return parseable;
    }

    public static void parse(List<Path> paths) {
        for (Path path : paths) {
            Meta meta = Parser.parseMeta(path);
            if (null != meta) {
                GsbRepo.addParseable(Parser.parseParseable(meta));
            }
        }
    }

    private static String parseLayout(String line) {
        int indexOf = line.indexOf('=');
        String substring = line.substring(indexOf + 1).trim();
        substring = substring.substring(1, substring.length() - 1);
        return substring.trim();
    }
}
